# -*- coding: utf-8 -*-
from wbhttp.WBLogin import WeiBoLogin
import pickle
import requests
import os
from logger import logger
from config import USER_NAME, PASSWD


class HttpClient(object):
    @staticmethod
    def post(url, data, headers=None, require_login=True):
        session = requests.session()
        if require_login == True:
            session.cookies = HttpClient.load_cookies()
        # set default U-A
        session.headers[
            "User-Agent"] = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"
        session.headers['Content-Type'] = 'application/x-www-form-urlencoded'

        if headers != None:
            for key in headers.keys():
                session.headers[key] = headers[key]
        return session.post(url, data=data)

    @staticmethod
    def get(url, headers=None, require_login=True):
        session = requests.session()

        if require_login == True:
            session.cookies = HttpClient.load_cookies()
        ## default User-Agent
        session.headers[
            "User-Agent"] = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"
        if headers != None:
            for key in headers.keys():
                session.headers[key] = headers[key]

        return session.get(url)

    @staticmethod
    def save_cookies(session):
        with open('.' + USER_NAME + '.txt', 'wb') as f:
            pickle.dump(session.cookies, f)
            f.close()
        return

    @staticmethod
    def load_cookies():
        if not os.path.exists('.' + USER_NAME + '.txt'):
            logger.info(u'还没有登录，立即登录')
            session = WeiBoLogin().login(USER_NAME, PASSWD)
            print(session)
            HttpClient.save_cookies(session)
            return session.cookies
        else:
            with open('.' + USER_NAME + '.txt', 'rb') as f:
                cookies = pickle.load(f)
                return cookies
        return None
